<template>
  <div class="specialty-form-container">
    <el-card class="form-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h2>商品信息管理</h2>
          <p>填写完整的商品信息</p>
        </div>
      </template>

      <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="specialty-form" @submit.prevent="handleSubmit">
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入商品名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品编码" prop="code">
                <el-input v-model="formData.code" placeholder="请输入商品编码" clearable />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="产地" prop="origin">
                <el-input v-model="formData.origin" placeholder="请输入产地" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="isEnabled">
                <el-switch v-model="formData.isEnabled" active-text="启用" inactive-text="禁用" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 价格信息 -->
        <div class="form-section">
          <h3 class="section-title">价格信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="原价" prop="originalPrice">
                <el-input-number v-model="formData.originalPrice" :min="0" :precision="2" placeholder="请输入原价" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="现价" prop="price">
                <el-input-number v-model="formData.price" :min="0" :precision="2" placeholder="请输入现价" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 产品信息 -->
        <div class="form-section">
          <h3 class="section-title">产品信息</h3>

          <el-form-item label="商品标签" prop="tagsJson">
            <div class="tags-container">
              <el-tag v-for="tag in tags" :key="tag" closable @close="removeTag(tag)" class="tag-item">
                {{ tag }}
              </el-tag>
              <el-input v-if="inputVisible" ref="inputRef" v-model="inputValue" size="small" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" class="tag-input" />
              <el-button v-else size="small" @click="showInput" class="add-tag-btn"> + 添加标签 </el-button>
            </div>
          </el-form-item>

          <el-form-item label="产品描述" prop="description">
            <el-input v-model="formData.description" type="textarea" :rows="4" placeholder="请输入产品描述" />
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="生产日期" prop="productionDate">
                <el-date-picker v-model="formData.productionDate" type="date" placeholder="选择生产日期" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="保质期(天)" prop="expirationDays">
                <el-input-number v-model="formData.expirationDays" :min="1" placeholder="请输入保质期天数" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="评分" prop="rating">
                <el-rate v-model="formData.rating" :max="5" allow-half show-score />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="销量" prop="saleCount">
                <el-input-number v-model="formData.saleCount" :min="0" placeholder="销量" style="width: 100%" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 产品图片 -->
        <div class="form-section">
          <h3 class="section-title">产品图片</h3>
          <el-form-item label="产品图片" prop="imageUrls">
            <el-upload :file-list="imageFileList" :headers="fileHeader" :action="formAction" list-type="picture-card" :on-success="handleImageUpload" :on-remove="handleImageRemove">
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="handleSubmit" size="large"> 发布商品 </el-button>
          <el-button @click="handleReset" size="large"> 重置表单 </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from 'vue'
import { create } from '@/apis/product'
import { ElMessage, ElMessageBox, type FormInstance, type UploadFile, type FormRules } from 'element-plus'
import { Delete, Plus } from '@element-plus/icons-vue'
import { dayjs } from 'element-plus'
// 表单引用
const formRef = ref<FormInstance>()
const inputRef = ref()

const host = import.meta.env.VITE_BASE_URL

const formAction = ref(host + '/api/sysFile/uploadFile')
const fileHeader = ref({
  Authorization: 'Bearer ' + localStorage.getItem('token')
})
const imageUrls = new Array()
const imageFileList = ref<UploadFile[]>([])
// 表单数据
const formData = reactive({
  name: '',
  code: '',
  origin: '东川区',
  originalPrice: 100,
  price: 10,
  tagsJson: '["熟食"]',
  description: '地道本地风味，选用优质食材。',
  productionDate: dayjs().format('YYYY-MM-DD'),
  expirationDays: 7,
  isEnabled: true,
  imageUrls: '',
  saleCount: 0,
  rating: 5
})

// 标签相关
const inputVisible = ref(false)
const inputValue = ref('')

// 计算属性 - 标签数组
const tags = computed({
  get: () => {
    try {
      return JSON.parse(formData.tagsJson || '[]')
    } catch {
      return []
    }
  },
  set: (value: string[]) => {
    formData.tagsJson = JSON.stringify(value)
  }
})

const handleImageUpload = (response: any) => {
  // console.log('Logo上传结果:', response)
  let { code, message, result } = response
  if (code === 200) {
    let url = `${host}/${result.url}`
    imageUrls.push(url)
    ElMessage.success('上传成功')
    console.log('上传成功', url)
  } else {
    ElMessage.error('Logo上传失败: ' + response.message)
  }
}

const handleImageRemove = (file: any) => {
  const currentImages = JSON.parse(formData.imageUrls || '[]')
  const index = imageFileList.value.findIndex((item) => item.uid === file.uid)
  if (index > -1) {
    currentImages.splice(index, 1)
    formData.imageUrls = JSON.stringify(currentImages)
  }
}

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入商品编码', trigger: 'blur' },
    { pattern: /^[A-Z0-9]+$/, message: '编码只能包含大写字母和数字', trigger: 'blur' }
  ],
  origin: [{ required: true, message: '请输入产地', trigger: 'blur' }],
  originalPrice: [
    { required: true, message: '请输入原价', trigger: 'blur' },
    { type: 'number', min: 0, message: '原价必须大于等于0', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入现价', trigger: 'blur' },
    { type: 'number', min: 0, message: '现价必须大于等于0', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入产品描述', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  productionDate: [{ required: true, message: '请选择生产日期', trigger: 'change' }],
  expirationDays: [
    { required: true, message: '请输入保质期天数', trigger: 'blur' },
    { type: 'number', min: 1, message: '保质期必须大于0天', trigger: 'blur' }
  ]
}

// 标签操作方法
const removeTag = (tag: string) => {
  const newTags = tags.value.filter((t: string) => t !== tag)
  tags.value = newTags
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value && !tags.value.includes(inputValue.value)) {
    tags.value = [...tags.value, inputValue.value]
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 表单操作方法
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 验证价格逻辑
    if (formData.price > formData.originalPrice) {
      ElMessage.warning('现价不能高于原价')
      return
    }

    const submitData = { ...formData }
    submitData.imageUrls = JSON.stringify(imageUrls)
    create(submitData)
      .then((response) => {
        const { code, message } = response.data
        if (code !== 200) {
          throw new Error(message || '提交失败')
        }
        ElMessage.success('商品信息保存成功！')
        // 重置表单
        formRef.value?.resetFields()
      })
      .catch((error) => {
        ElMessage.error(error.message || '提交失败，请稍后再试')
      })
    // console.log('提交数据:', submitData)
  } catch (error) {
    ElMessage.error('请检查表单填写是否正确')
  }
}

const handleReset = async () => {
  try {
    await ElMessageBox.confirm('确定要重置表单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    formRef.value?.resetFields()
    ElMessage.success('表单已重置')
  } catch {
    // 用户取消
  }
}
</script>

<style scoped>
.specialty-form-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.form-card {
  border-radius: 12px;
  overflow: hidden;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.card-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.specialty-form {
  padding: 20px 0;
}

.form-section {
  margin-bottom: 32px;
  padding: 24px;
  background: #fafafa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.section-title {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  margin: 0;
}

.tag-input {
  width: 120px;
}

.add-tag-btn {
  border-style: dashed;
}

.image-upload-container {
  width: 100%;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 16px;
}

.image-item {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  border: 2px solid #e4e7ed;
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-item:hover .image-overlay {
  opacity: 1;
}

.upload-area {
  display: flex;
  gap: 12px;
  align-items: center;
}

.url-input {
  flex: 1;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding-top: 24px;
  border-top: 1px solid #e4e7ed;
}

.preview-content {
  max-height: 400px;
  overflow-y: auto;
}

.preview-content pre {
  background: #f5f5f5;
  padding: 16px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.5;
}

@media (max-width: 768px) {
  .specialty-form-container {
    padding: 10px;
  }

  .form-section {
    padding: 16px;
  }

  .form-actions {
    flex-direction: column;
  }

  .form-actions .el-button {
    width: 100%;
  }
}
</style>
